import Taro, { Component, Config, getCurrentPages } from '@tarojs/taro'
import { AtList, AtListItem, AtButton, AtIcon, AtCurtain } from 'taro-ui'
import { View, Text, Image } from '@tarojs/components'
import { observer, inject } from '@tarojs/mobx'
import '@tarojs/async-await'
import Stores from '../../../stores/storeIdentifier'
import { OrderStatus } from "../../../services/order/dto/OrderStatus"
import './detail.scss'
import OrderStore from '../../../stores/orderStore'
import { OrderDto } from '../../../services/order/dto/orderDto'
import moment from "moment"
// import _ from 'lodash'
import ProductStore from '../../../stores/productStore'
import { PagedList } from '../../../services/dto/pagedList'
import { ProductListDto } from '../../../services/product/dto/productListDto'
import { JsApiReturnModel } from '../../../services/dto/jsApiReturnModel'
import { PayResultModel } from '../../../services/dto/payResultModel'
import { UserShippingAddressDto } from '../../../services/cart/dto/userShippingAddressDto'
import WxOpenStore from '../../../stores/wxOpenStore';

export interface IDetailProps {
  orderStore: OrderStore,
  productStore: ProductStore,
  wxOpenStore: WxOpenStore
}

@inject(Stores.OrderStore, Stores.ProductStore, Stores.WxOpenStore)
@observer
class Detail extends Component<IDetailProps> {
  jsApiModel: JsApiReturnModel
  order: OrderDto
  creationTime: string
  payTime: string
  products: PagedList<ProductListDto>
  isLoading: boolean = true
  payResult: PayResultModel
  commented: boolean = false
  defaultAddress: UserShippingAddressDto
  state = {
    skipCount: 0,
    isOpened: false,
    sorting: 'id desc',
    maxResultCount: 10
  }
  constructor(props) {
    super(props)
  }

  config: Config = {
    navigationBarTitleText: '订单详情'
  }

  async componentWillMount() {
    await this.getOrderDetail()
    await this.getProducts()
  }

  async componentDidShow() {
    var pages = getCurrentPages()

    if (pages.length >= 2) {
      let prevPage = pages[pages.length - 2]
      prevPage.setData({
        orderFlag: true
      })
    }
    if (pages) {
      let prev = pages[pages.length - 1]
      if (prev.data.defaultAddress) {
        this.defaultAddress = prev.data.defaultAddress
        await this.changeOrderAddress()
      }
    }
    this.setState({})
  }

  async changeOrderAddress() {
    await this.props.orderStore.changeOrderUserShippingAddress(this.defaultAddress.id, this.$router.params.id)
    this.order.receiptUserName = this.defaultAddress.receiptUserName
    this.order.mobilephone = this.defaultAddress.mobilephone
    this.order.areaCodeDisplayName = this.defaultAddress.areaCodeDisplayName
    this.order.address = this.defaultAddress.address
    this.setState({})
  }

  getProducts = async () => {
    await this.props.productStore.getProductPagedListAsync({
      sorting: this.state.sorting,
      maxResultCount: this.state.maxResultCount,
      skipCount: this.state.skipCount
    })

    this.products = this.props.productStore.products
    this.setState({})
  }

  async getOrderDetail() {
    await this.props.orderStore.getMyOrderDetail(this.$router.params.id)
    this.order = this.props.orderStore.order;
    // if (this.order.orderStatusHistories)
    //   this.order.orderStatusHistories = _.orderBy(this.order.orderStatusHistories, ['status'], ['asc'])
    this.setState({})
  }

  getTitleForStatus(status: OrderStatus) {
    switch (status) {
      case OrderStatus.WaitPay:
        return '创建时间：'
      case OrderStatus.PaidAndWaitShip:
        return '付款时间：'
      case OrderStatus.ShippedAndWaitReceipt:
        return '发货时间：'
      case OrderStatus.Completed:
        return '完成时间：'
    }
  }

  async confirmResolve() {
    await this.props.orderStore.confirmReceive(this.$router.params.id)
    await this.getOrderDetail()
  }

  gotoExpress(code, number, e) {
    Taro.navigateTo({
      url: '/pages/profile/order/logistics?code=' + code + '&express=' + number
    })
  }

  gotoComment() {
    Taro.navigateTo({ url: '/pages/profile/order/comment-list?id=' + this.$router.params.id })
  }

  onGetPay = async () => {
    if (!this.defaultAddress && !this.order.receiptUserName) {
      this.gotoAddrss()
    }

    await this.props.orderStore.getApiPay(this.$router.params.id)
    this.jsApiModel = this.props.orderStore.jsApiModel

    if (this.jsApiModel) {
      var _package = this.jsApiModel.package as string
      var _prepay_id = _package.replace('prepay_id=', '')
      await this.props.wxOpenStore.createFormIds([{ formId: _prepay_id, formIdType: 1 }])
      let this_ = this
      Taro.requestPayment({
        timeStamp: this.jsApiModel.timestamp,
        nonceStr: this.jsApiModel.nonceStr,
        package: this.jsApiModel.package,
        signType: this.jsApiModel.signType,
        paySign: this.jsApiModel.paySign,
        async success(res) {

          this_.setState({isOpened: true});
          this_.getPayStatus()
        },
      }).then((res) => {

      })
    }
  }

  async getPayStatus() {
    if (this.isLoading) {
      await this.props.orderStore.getPayStatus(this.$router.params.id)
      this.payResult = this.props.orderStore.payResult
      if (this.payResult.isSuccess) {
        this.isLoading = false
        this.getOrderDetail()
        this.setState({}, async () => {
          await this.getPayStatus()
        })
      }
    }
  }

  onClose() {
    this.setState({
      isOpened: false
    })
  }

  onCancelOrder = async () => {
    await this.props.orderStore.cancelOrder(this.$router.params.id)
    await this.getOrderDetail()
  }

  async deleteOrder() {
    await this.props.orderStore.deleteOrder(this.$router.params.id)
    Taro.navigateBack({ delta: 1 })
  }

  gotoProduct(id, e) {
    Taro.redirectTo({ url: '/pages/product/index?id=' + id })
  }

  gotoAddrss() {
    Taro.navigateTo({ url: '/pages/profile/address/index?prev=order&ids=' + this.$router.params.ids })
  }

  render() {
    return (
      this.order ?
        <View className='order-wrap'>
          {!this.order.receiptUserName && (
            <View className='no-address' onClick={this.gotoAddrss}>
              <AtButton type='primary' size='small'><AtIcon value='map-pin' size='16' />添加收货地址</AtButton>
            </View>
          )}
          <View className='order-address'>
            {
              this.order.receiptUserName &&
              <View className='address-item ratina-bd bd-b'>
                <View className='addr-hd'>
                  <Text className='name'>{this.order.receiptUserName}</Text>
                </View>
                <View className='addr-bd'>
                  <Text className='tel'>{this.order.mobilephone}</Text>
                  <Text className='addr-disc'>{this.order.areaCodeDisplayName}{this.order.address}</Text>
                </View>
              </View>
            }
          </View>

          <View className='order-panel ratina-bd bd-t'>
            <View className='order-panel-header ratina-bd bd-b'>
              <Text>包裹1</Text>
              <Text className='danger'>{this.order.statusDisplayName}</Text>
            </View>
            <View className='order-panel-body'>
              {
                this.order.orderItems.map((item) => (
                  <View className='order-info ratina-bd bd-b' onClick={this.gotoProduct.bind(this, item.productId)}>
                    <View className='media'>
                      <Image mode='aspectFill' src={item.featuredImage} />
                      <View className='media-bd'>
                        <View className='h4'>{item.productName}</View>
                        {item.skuName && <View className='p'>{item.skuName}</View>}
                      </View>
                    </View>
                    <View className='tips'>
                      <Text>x{item.quantity}</Text>
                    </View>
                  </View>
                ))
              }
            </View>
          </View>
          <View className='row-list ratina-bd bd-t bd-b'>
            <View className='row-item'>订单编号：{this.order.id}</View>
            {
              this.order && this.order.orderStatusHistories && this.order.orderStatusHistories.map((item) => (
                <View className='row-item'>
                  {
                    this.getTitleForStatus(item.status) && this.getTitleForStatus(item.status) + moment(item.creationTime).format('YYYY-MM-DD HH:mm:ss')
                  }
                </View>
              ))
            }
          </View>
          <AtList>
            <AtListItem title='商品合计' extraText={'￥' + this.order.finalPrice} />
            {/* <AtListItem title='运费' extraText='￥10.00' />
          <AtListItem hasBorder={false} title='活动优惠' extraText='-￥10.00' /> */}
          </AtList>

          {this.order && this.order.status.toString() === OrderStatus.WaitPay.toString() &&
            <View className='zhifu-btn-wrap'>
              <AtButton type='primary' onClick={this.onGetPay}>立即支付</AtButton>
            </View>}
          {this.order && this.order.status.toString() === OrderStatus.ShippedAndWaitReceipt.toString() &&
            <View className='fixed-btn ratina-bd bd-t'>
              {this.order.express &&
                <AtButton type='secondary' size='small' onClick={this.gotoExpress.bind(this, this.order.express!.code100, this.order.expressNumber)}>查看物流</AtButton>}
              <AtButton type='secondary' size='small' onClick={this.confirmResolve}>确认收货</AtButton>
            </View>}
          {this.order && this.order.status.toString() === OrderStatus.Completed.toString() &&
            <View className='fixed-btn ratina-bd bd-t'>
              {/* {this.order.shouldComment && <AtButton type='secondary' size='small' onClick={this.gotoComment}>评价</AtButton>} */}
              {/* <AtButton type='secondary' size='small' onClick={this.repeatBuy}>再次购买</AtButton>} */}
              {this.order.express && <AtButton type='secondary' size='small' onClick={this.gotoExpress.bind(this, this.order.express!.code100, this.order.expressNumber)}>查看物流</AtButton>}
              <AtButton type='primary' size='small' onClick={this.deleteOrder}>删除</AtButton>
            </View>}
          <AtCurtain
            isOpened={this.state.isOpened}
            onClose={this.onClose.bind(this)}
            closeBtnPosition='top right'
          >
            <Image
              style='width:100%;height:200px'
              src='http://www.51yuanliang.com/images/miniapp/pay-result.png'
              mode='aspectFit'
            />
          </AtCurtain>
        </View> :
        <View className='order-wrap'></View>
    )
  }
}

export default Detail
